<?php

namespace Admin\Action;

/**
 * ============================================================================
 * MXCMall开源商城
 * 官网地址:http://www.mothink.cn
 * 联系QQ:510858687
 * ============================================================================
 * 店铺控制器
 */
class ShopsAction extends BaseAction {

    /**
     * 跳到新增/编辑页面
     */
    public function toEdit() {
        $this->isLogin();
        //获取商品信息
        $m = D('Admin/Shops');
        $object = array();
        if (I('id', 0) > 0) {
            $this->checkPrivelege('ppgl_02');
            $object = $m->getShopAuth();
        }
        $deposit = M('shops_deposit')->select();

        $this->assign('deposit', $deposit);
        $this->assign('src', I('src'));
        $this->assign('object', $object);

        $this->view->display('/shops/shop_auth');
    }

    public function upShop() {
        $shopId = I('shopId', 0);
        if ($shopId > 0) {
            $m = M('shops');
            $m->where('shopId=' . $shopId)->save(array('shopStatus' => I('shopStatus'), 'depositId' => I('depositId'), 'depositMoney' => I('depositMoney')));
            $_remark = I('remark');
            if (!empty($_remark)) {
                $m = M('shops_auth');
                $m->where('shopId=' . $shopId)->save(array('remark' => I('remark')));
            }
            $oldShopStatus = I('oldShopStatus');
            if ($oldShopStatus == -2 && I('shopStatus') != -2) {
                $goods = M('log_stop_shop_goods')->where('shopId = ' . $shopId)->order('id desc')->find();
                if (!empty($goods)) {
                    $goodsIds = $goods['sourceGoods'] . ',' . $goods['resaleGoods'] . ',' . $goods['reToMygoods'];
                    $goodsIds = trim($goodsIds, ',');
                    M('goods')->where('goodsId in (' . $goodsIds . ')')->save(array('goodsStatus' => 1));
                    M('log_stop_shop_goods')->where('id=' . $goods['id'])->delete();
                }
            }
            $src = I('src');
            if ($src == 'index') {
                $this->success('Success!', 'index');
            } else {
                $this->success('Success!', 'queryPeddingByPage');
            }

            exit;
        }
        $this->error('Error!');
    }

    /**
     * 新增/修改操作
     */
    public function edit() {
        $this->isAjaxLogin();
        $m = D('Admin/Shops');
        $rs = array();
        if (I('id', 0) > 0) {
            $this->checkAjaxPrivelege('ppgl_02');
            if (I('shopStatus', 0) <= -1) {
                $rs = $m->reject();
            } else {
                $rs = $m->edit();
            }
        } else {
            $this->checkAjaxPrivelege('ppgl_01');
            $rs = $m->insert();
        }
        $this->ajaxReturn($rs);
    }

    /**
     * 删除操作
     */
    public function del() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('ppgl_03');
        $m = D('Admin/Shops');
        $rs = $m->del();
        $this->ajaxReturn($rs);
    }

    /**
     * 冻结店铺
     */
    public function stop() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('ppgl_03');
        $m = D('Admin/Shops');
        $rs = $m->stop();

        $this->ajaxReturn($rs);
    }

    /**
     * 冻结店铺
     */
    public function closeShop() {
        $this->isAjaxLogin();
        $this->checkAjaxPrivelege('ppgl_03');
        $m = D('Admin/Shops');
        $rs = $m->closeShop();

        $this->ajaxReturn($rs);
    }

    /**
     * 查看
     */
    public function toView() {
        $this->isLogin();
        $this->checkPrivelege('ppgl_00');
        $m = D('Admin/Shops');
        if (I('id') > 0) {
            $object = $m->get();
            $this->assign('object', $object);
        }
        $this->view->display('/shops/view');
    }

    /**
     * 分页查询
     */
    public function index() {
        $this->isLogin();
        $this->checkPrivelege('ppgl_00');
        //获取地区信息
        $m = D('Admin/Areas');
        $this->assign('areaList', $m->queryShowByList(0));
        $m = D('Admin/Shops');
        $page = $m->queryByPage();

        $pager = new \Think\Page($page['total'], $page['pageSize']); // 实例化分页类 传入总记录数和每页显示的记录数
        $page['pager'] = $pager->show();
       // foreach ($page['root'] as $key => &$value) {
      //      $value['username'] = M('Users')->where(array('userId'=>$value['userId']))->getField('userName');
      //  }
//echo "<pre>";
//var_dump($page['root']); die;
        $this->assign('Page', $page);
        $this->assign('fullName', I('fullName'));
        $this->assign('areaId1', I('areaId1', 0));
        $this->assign('areaId2', I('areaId2', 0));
        $this->display("/shops/list");
    }

    /**
     * 分页查询[待审核列表]
     */
    public function queryPeddingByPage() {
        $this->isLogin();
        $this->checkPrivelege('dpsh_00');
        //获取地区信息
        $m = D('Admin/Areas');
        $this->assign('areaList', $m->queryShowByList(0));
        $m = D('Admin/Shops');
        $page = $m->queryPeddingByPage();
        $pager = new \Think\Page($page['total'], $page['pageSize']);
        $pager->setConfig('header', '');
        $page['pager'] = $pager->show();
        $this->assign('Page', $page);
        $this->assign('shopName', I('shopName'));
        $this->assign('shopSn', I('shopSn'));
        $this->assign('shopStatus', I('shopStatus', -999));
        $this->assign('areaId1', I('areaId1', 0));
        $this->assign('areaId2', I('areaId2', 0));
        $this->display("/shops/list_pendding");
    }

    /**
     * 列表查询
     */
    public function queryByList() {
        $this->isAjaxLogin();
        $m = D('Admin/Shops');
        $list = $m->queryList();
        $rs = array();
        $rs['status'] = 1;
        $rs['list'] = $list;
        $this->ajaxReturn($rs);
    }

    /**
     * 获取待审核的店铺数量
     */
    public function queryPenddingGoodsNum() {
        $this->isAjaxLogin();
        $m = D('Admin/Shops');
        $rs = $m->queryPenddingShopsNum();
        $this->ajaxReturn($rs);
    }

    /**
     * 保证金列表
     */
    public function deposit() {
        $this->isLogin();
        $m = M('shops_deposit');
        $lists = $m->where(1)->order('level ASC')->select();

        $this->assign('lists', $lists);
        $this->display("/shops/list_deposit");
    }

    public function addDeposit() {
        $this->isLogin();
        if (IS_POST) {
            $img = $this->uploadImg('icon');

            $m = M('shops_deposit');
            if (I('id', 0) > 0) {
                $data = array();
                $data['level'] = I('level');
                if (!empty($img['picPath'])) {
                    $data['icon'] = $img['picPath'];
                }
                $data['money'] = I('money');
                $data['goodsNum'] = I('goodsNum');
                $data['resaleNum'] = I('resaleNum');
                $data['title'] = I('title');
                $data['description'] = I('description');
                foreach ($data as $v) {
                    if ($v == '')
                        $this->error('请填写完整信息!');
                }

                $rs = $m->where('id=' . I('id'))->save($data);
                if ($rs !== FALSE) {
                    $this->success('Success!', 'deposit');
                } else {
                    $this->error('Error!');
                }
            } else {
                $data = array();
                $data['level'] = I('level');
                $data['money'] = I('money');
                $data['goodsNum'] = I('goodsNum');
                $data['resaleNum'] = I('resaleNum');
                $data['title'] = I('title');
                $data['description'] = I('description');
                if (!empty($img['picPath'])) {
                    $data['icon'] = $img['picPath'];
                } else {
                    $data['icon'] = '';
                }

                foreach ($data as $v) {
                    if ($v == '')
                        $this->error('请填写完整信息!');
                }

                $rs = $m->add($data);
                if ($rs !== FALSE) {
                    $this->success('Success!', 'deposit');
                } else {
                    $this->error('Error!');
                }
            }
        } else {
            if (I('id', 0) > 0) {
                $m = M('shops_deposit');
                $object = $m->where('id=' . I('id'))->find();
                $this->assign('object', $object);
            }

            $this->display("/shops/add_deposit");
        }
    }

    public function delDeposit() {
        $this->isAjaxLogin();
        $rt = array();
        $rt['status'] = 0;
        if (I('id', 0) > 0) {
            $m = M('shops_deposit');
            $rs = $m->where('id=' . I('id'))->delete();
            if ($rs !== FALSE)
                $rt['status'] = 1;
            $this->ajaxReturn($rt);
        }

        $this->ajaxReturn($rt);
    }

    /**
     * 设置推荐
     */
    public function changeRecom() {
        $this->isAjaxLogin();
        $rt = array();
        $rt['status'] = 0;
        if (I('id', 0) > 0) {
            $m = M('shops');
            $m->isRecom = I('isRecom');
            $rs = $m->where('shopId=' . I('id'))->save();

            if ($rs !== FALSE)
                $rt['status'] = 1;
            $this->ajaxReturn($rt);
        }

        $this->ajaxReturn($rt);
    }


    /**
     * [adminCreateShop description] 后台管理创建店铺
     * @return [type] [description]
     */
    public function adminCreateShop(){

        $data = array();
        $userPhone = $this->randpw(3,'CHAR').time() ;
        $data['userPhone'] = '';
        $createLoginPwd = $this->randpw(6,'ALL');
        $createLoginPwd = strtolower($createLoginPwd); 
        
        $data['loginName'] = $userPhone;
        $data['userName'] = $userPhone;
        $data['IsAdminCreatea'] = '1';

 
        //检测账号，邮箱，手机是否存在
        $data["loginSecret"] = rand(1000, 9999);
        $data['loginPwd'] = md5($createLoginPwd. $data['loginSecret']);
        $data['userType'] = 0;
        $data['createTime'] = date('Y-m-d H:i:s');
        $data['userFlag'] = 1;

        $m = M('users');   
        $rs = $m->add($data);
         
        
        if (false !== $rs) {
            $rd['status'] = 1;
            $rd['userId'] = $rs;
            $rd['msg'] = '注册成功!';
           // $this->success('Success!', $rd['msg']);
            $data['createLoginPwd'] = $createLoginPwd;
            $this->adminCreateShopName($data,$rs);
        }  else {
            $this->error('Error!', '注册失败');
        }
    }

    private function adminCreateShopName($param,$recId) {

       // $CreateInfo  = '系统第一次生成的用户登录名:'.$param['userName'];
        $CreateInfo  = "登录密码:".$param['createLoginPwd'] ;
   
        $this->assign('userId',$recId);
        $this->assign('createUserInfo',$CreateInfo);
        $this->display("shops/adminCreateShop");
    }

    public function postCreateShop() {
 
        
        $this->isLogin();
        if (!IS_POST) {
           $this->error('数据不是POST，不能通过!');     
        }

        if (false==$_POST['shopName']){
            $this->error('请填写店铺名称!');
            exit;
        }
        if (false==$_POST['fullName']){
            $this->error('请填写联系人!');
            exit;
        }
        if (false==$_POST['phone']){
            $this->error('请填写手机号!');
            exit;
        }

        
        $uCount= M('User')->where(array('userPhone'=>$_POST['phone']))->count();
        if ($uCount>0) {
            $this->error('手机号已经注册存在，不能重复使用');
            exit;
        }

        $img = array();
        if ($_FILES) {
            $img = $this->uploadImg('shopImg');
        }
        

        $save = array();
        $save['shopName'] = $_POST['shopName'];
        $save['fullName'] = $_POST['fullName'];
        $save['userId'] = $userId = $_POST['userId'];
        $save['shopTel'] = $_POST['phone'];
        $save['shopImg'] = $img['picPath'];
        $save['IsAdminCreate'] = '1';
        $save['adminCreateInfo'] = $_POST['createUserInfo'];
    
        $save['shopStatus'] = 1;
        $save['shopFlag'] = 1;

 
        $rs= $shopId= M('shops')->add($save);
        if ($rs !== FALSE) {
            $this->setRongCloudUserToke($userId, $_POST['phone']);
            M('shops')->where('shopId=' . $shopId)->save(array('shopSN' => 100000 + $shopId));

            $m_users = M('users');   
            $m_users->where(array('userId'=>$userId))->save(array('loginName'=>$_POST['phone'],'userPhone'=>$_POST['phone']));
            /////
            $auth = array();
            $auth['shopId'] = $rs;
            $auth['shopType'] = 2;
            $auth['phone'] = $_POST['phone'];
            $auth['fullName'] =  $_POST['fullName'];
            //
            $auth['areaId1'] = '';
            $auth['areaId2'] = '';
            $auth['areaId3'] = '';
            $auth['province'] = '';
            $auth['city'] = '';
            $auth['district'] = '';
            $auth['address'] = '';
            $auth['cardNum'] = '';
            $auth['cardImg'] = '';
            $auth['userCardImg'] = '';
            $auth['company'] = '';
            $auth['companyNum'] = '';
            $auth['companyAddress'] = '';
            $auth['companyImg'] = '';
            $auth['remark'] = '';

            $m = M('shops_auth');
            $authId = $m->add($auth);
            if ($authId>0) {
                    M('users')->where(array('userId' => $userId))->save(array('userType' => 2));
                }
            $this->success('Success!', 'index.html');
        } else {
            $this->error('Error!');
        }

             

         

    }


     /**
     * 获取融云TOKEN
     * @return type
     */
    public function setRongCloudUserToke($uid, $name) {
        $appKey = 'e5t4ouvptfp1a';
        $appSecret = 'LXLYdXbNnE3';

        vendor("RongCloud.ServerAPI");
        $rongCloud = new \RongServerAPI($appKey, $appSecret);

//        $uid = 1;
//        $name = '13751082273';
        $portraitUri = C('WEB_URL') . '/Public/images/default_haeder.png';
        $token = $rongCloud->getToken($uid, $name, $portraitUri);
        $token = json_decode($token, TRUE);
        $rs = M('users')->where('userId=' . $uid)->save(array('rongToken' => $token['token']));
        return $rs;
    }


}

?>